<template>
  <div class="dict-data-container">
    <!-- 页面头部 -->
    <el-card class="header-card">
      <div class="page-header">
        <div class="header-left">
          <el-button :icon="ArrowLeft" @click="goBack">返回</el-button>
          <div class="dict-info">
            <h2 class="dict-name">{{ dictName }}</h2>
            <el-tag type="primary">{{ dictType }}</el-tag>
          </div>
        </div>
        <div class="header-actions">
          <el-button type="primary" :icon="Plus" @click="handleAdd">新增数据</el-button>
          <el-button type="success" :icon="Download" @click="handleExport">导出</el-button>
          <el-button type="warning" :icon="Refresh" @click="refreshPage">刷新</el-button>
        </div>
      </div>
    </el-card>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true">
        <el-form-item label="字典标签：" prop="dictLabel">
          <el-input
            v-model="queryParams.dictLabel"
            placeholder="请输入字典标签"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="字典键值：" prop="dictValue">
          <el-input
            v-model="queryParams.dictValue"
            placeholder="请输入字典键值"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="所有" value="" />
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="dictDataList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="dictLabel" label="字典标签" min-width="120" />
        <el-table-column prop="dictValue" label="字典键值" min-width="120" />
        <el-table-column prop="dictSort" label="字典排序" width="100" align="center" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
              {{ scope.row.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isDefault" label="是否默认" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isDefault === 'Y' ? 'success' : 'info'">
              {{ scope.row.isDefault === 'Y' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="160" align="center">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              :icon="Edit"
              @click="handleEdit(scope.row)"
            >修改</el-button>
            <el-button
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNumber"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/修改对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="字典标签" prop="dictLabel">
          <el-input v-model="formData.dictLabel" placeholder="请输入字典标签" />
        </el-form-item>
        <el-form-item label="字典键值" prop="dictValue">
          <el-input v-model="formData.dictValue" placeholder="请输入字典键值" />
        </el-form-item>
        <el-form-item label="字典排序" prop="dictSort">
          <el-input-number 
            v-model="formData.dictSort" 
            :min="0" 
            :max="999"
            placeholder="请输入排序"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否默认" prop="isDefault">
          <el-radio-group v-model="formData.isDefault">
            <el-radio label="Y">是</el-radio>
            <el-radio label="N">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="样式类名" prop="cssClass">
          <el-input v-model="formData.cssClass" placeholder="请输入样式类名" />
        </el-form-item>
        <el-form-item label="列表样式" prop="listClass">
          <el-input v-model="formData.listClass" placeholder="请输入列表样式" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Download, 
  Edit, 
  Delete, 
  ArrowLeft
} from '@element-plus/icons-vue'
import { getDictDataList, addDictData, updateDictData, deleteDictData } from '@/api/dict'

const route = useRoute()
const router = useRouter()

// 从路由参数获取字典信息
const dictType = ref(route.query.dictType || '')
const dictName = ref(route.query.dictName || '')

// 搜索表单
const queryParams = reactive({
  dictLabel: '',
  dictValue: '',
  status: '',
  dictType: dictType.value,
  pageNumber: 1,
  pageSize: 10
})

// 表格数据
const loading = ref(false)
const dictDataList = ref([])
const total = ref(0)

// 对话框
const dialog = reactive({
  visible: false,
  title: ''
})

// 表单数据
const formData = ref({
  dictCode: undefined,
  dictLabel: '',
  dictValue: '',
  dictSort: 0,
  dictType: dictType.value,
  cssClass: '',
  listClass: '',
  isDefault: 'N',
  status: '0',
  remark: ''
})

// 表单验证规则
const formRules = {
  dictLabel: [
    { required: true, message: '字典标签不能为空', trigger: 'blur' }
  ],
  dictValue: [
    { required: true, message: '字典键值不能为空', trigger: 'blur' }
  ],
  dictSort: [
    { required: true, message: '字典排序不能为空', trigger: 'blur' }
  ]
}

// 引用
const queryFormRef = ref()
const formRef = ref()

// 生命周期
onMounted(() => {
  if (!dictType.value) {
    ElMessage.error('缺少字典类型参数')
    goBack()
    return
  }
  getList()
})

// 获取列表数据
const getList = async () => {
  try {
    loading.value = true
    const response = await getDictDataList(queryParams)
    dictDataList.value = response.items
    total.value = response.totalCount
  } catch (error) {
    console.error('获取字典数据列表失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 刷新页面
const refreshPage = () => {
  getList()
  ElMessage.success('刷新成功')
}

// 搜索
const handleQuery = () => {
  queryParams.pageNumber = 1
  getList()
}

// 重置搜索
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  queryParams.pageNumber = 1
  getList()
}

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNumber = val
  getList()
}

// 新增
const handleAdd = () => {
  dialog.visible = true
  dialog.title = '新增字典数据'
  formData.value = {
    dictCode: undefined,
    dictLabel: '',
    dictValue: '',
    dictSort: dictDataList.value.length + 1,
    dictType: dictType.value,
    cssClass: '',
    listClass: '',
    isDefault: 'N',
    status: '0',
    remark: ''
  }
}

// 修改
const handleEdit = (row) => {
  dialog.visible = true
  dialog.title = '修改字典数据'
  formData.value = { ...row }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确认删除字典数据"${row.dictLabel}"吗？`, '提示', {
      type: 'warning'
    })
    
    await deleteDictData(row.dictCode)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate()
  
  try {
    const currentTime = new Date().toISOString()
    
    if (formData.value.dictCode) {
      // 修改操作
      await updateDictData({
        ...formData.value,
        updateBy: 'admin',
        updateTime: currentTime
      })
      ElMessage.success('修改成功')
    } else {
      // 新增操作
      await addDictData({
        ...formData.value,
        createBy: 'admin',
        createTime: currentTime,
        updateBy: 'admin',
        updateTime: currentTime
      })
      ElMessage.success('新增成功')
    }
    
    dialog.visible = false
    getList()
  } catch (error) {
    ElMessage.error(error.response?.data || '操作失败')
  }
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能待实现')
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}
</script>

<style scoped>
.dict-data-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.header-card {
  margin-bottom: 20px;
  background: white;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.dict-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.dict-name {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.search-card {
  margin-bottom: 20px;
  background: white;
}

.table-card {
  margin-bottom: 20px;
  background: white;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }

  .search-form :deep(.el-form-item) {
    width: 100% !important;
    margin-bottom: 10px;
  }

  .search-form :deep(.el-input),
  .search-form :deep(.el-select) {
    width: 100% !important;
  }
}
</style>